<template>
  <div class="login">
      <van-nav-bar
  title="标题"/>
  <van-cell-group>
  <van-field
    v-model="mobile"
    label="手机号"
    placeholder="请输入手机号"
    required
    :error-message="mobile_err"

  />
  <van-field
    v-model="code"
    label="验证码"
    placeholder="请输入验证码"
    required
    :error-message="code_err"

  />
  <div style="margin: 16px;">
    <van-button round block type="info" @click='login'>提交</van-button>
    <van-button type="info" @click='getUserInfo'>获取</van-button>
  </div>
</van-cell-group>
  </div>
</template>

<script>

import { resLogin, reqGetProfile } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '13912345611',
      code: '246810',
      mobile_err: '',
      code_err: ''
    }
  },
  methods: {
    valdate () {
      // 表单校验
      if (this.mobile.length === 0) {
        console.log(123)
        this.mobile_err = '请输入手机号'
        return false
      }
      // 手机号合法性
      if (!/^1[0-9]{10}$/.test(this.mobile)) {
        this.mobile_err = '请输入正确11位手机号'
        console.log(111)
        return false
      }
      this.mobile_err = ''
      if (this.code.length === 0) {
        this.code_err = '请输入验证码'
        return false
      }
      // 验证码合法性
      if (!/^\d{6}$/.test(this.code)) {
        this.code_err = '请输入正确验证码'
        return false
      }
      this.code_err = ''
      return true
    },
    async login () {
      Toast.loading({
        overlay: true,
        message: '加载中...',
        forbidClick: true
      })
      if (this.valdate()) {
        // const res = await this.instance.post('v1_0/authorizations', {
        //   mobile: this.mobile,
        //   code: this.code
        // })
        const res = await resLogin(this.mobile, this.code)
        console.log(res.data.data)
        // token存储
        Toast.success('成功文案')// 加模块名!
        this.$store.commit('user/setTokenInfo', res.data.data)
      }
      // this.$router.push('/')
      // 判断路由地址是否包含backTo字段,有这个字段 应该让他去backTo对应页面 没有就去首页
      if (this.$route.query.backTo) {
        this.$router.back() // push会新增历史记录
      } else {
        this.$router.push('/')
      }
    },
    async getUserInfo () {
      console.log('22222')
      const res = await reqGetProfile()
      console.log(res)
    }
  }
}
</script>

<style lang='scss' scoped>
.login {
  .btn-wrap {
    padding: 20px;
    .van-button--info {
      width: 100%;
      color: #fff;
      border-radius: 5px;
    }
  }
}
</style>
